﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Drawing;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraTreeList;
using DevExpress.XtraTreeList.Nodes;
using forever.Gobal;

namespace gencode.UI
{
    public partial class ucGenerateByTable : UserControl
    {
        private List<string> sMethodNames = new List<string>();
        //1: select; 2: update; 3: delete; 4: insert; 5:page;
        private List<string> sMethodType = new List<string>();
        private List<string> sMethodDescription = new List<string>();
        private List<string> sWhereType = new List<string>();
        private List<DataTable> sFieldDisplays = new List<DataTable>();
        private List<DataTable> sFieldConditions = new List<DataTable>();
        private string db, table;
        private DataTable dt;
        private DataTable dtUnique;
        private DataTable dtPK;
        private DataTable dtFK;
        private DataTable dtNotIdentitys;
        private DataTable dtChanges;
        private DataTable dtDefault;
        public ucGenerateByTable()
        {
            InitializeComponent();
        }
        public ucGenerateByTable(string _db, string _table)
        {
            InitializeComponent();
            this.db = _db;
            this.table = _table;
            dt = Gobal.SelectColumnNames(db, table);
            dtDefault = Gobal.SelectColumnNamesNotRows(db, table);
            dtFK = Gobal.SelectColumnsByConstraintType(db, table, "FOREIGN KEY");
            dtPK = Gobal.SelectColumnsByConstraintType(db, table, "PRIMARY KEY");
            dtUnique = Gobal.SelectColumnsByConstraintType(db, table, "UNIQUE");
            dtNotIdentitys = Gobal.SelectColumnByNotColumnIdentitys(db, table);
            init();
            //generateDefault();
        }
        void init()
        {
            txtBLL.Text = ConfigurationSettings.AppSettings["modifiersBLL"];
            txtDAL.Text = ConfigurationSettings.AppSettings["modifiersDAL"];
            txtDTO.Text = ConfigurationSettings.AppSettings["modifiersDTO"];
            txtView.Text = ConfigurationSettings.AppSettings["modifiersView"];
            txtBusinessLogicLayer.Text = ConfigurationSettings.AppSettings["BusinessLogicLayer"];
            txtDataAccessLayer.Text = ConfigurationSettings.AppSettings["DataAccessLayer"];
            txtPresentationLayer.Text = ConfigurationSettings.AppSettings["PresentationLayer"];
            txtDataObjectLayer.Text = ConfigurationSettings.AppSettings["DataObjectLayer"];
            txtUserClass.Text = ConfigurationSettings.AppSettings["user"];
            txtSproc.Text = ConfigurationSettings.AppSettings["modifierSproc"];
            txtDescriptionClass.Text = txtTableName.Text = table;
            txtNamespaceParent.Text = db;
            //
            DataTable dtChanges0 = Gobal.SelectColumnNames_customer(db, table);
            chksSFielDisplayed.DataSource = dtChanges0;
            chksSFielDisplayed.DisplayMember = "COLUMN";
            chksSFielDisplayed.ValueMember = "COLUMN_NAME";
            chksSFieldConditions.DataSource = dtChanges0;
            chksSFieldConditions.DisplayMember = "COLUMN";
            chksSFieldConditions.ValueMember = "COLUMN_NAME";
            //
            for (int i = 0; i < chksSFielDisplayed.ItemCount; i++)
                chksSFielDisplayed.SetItemChecked(i, true);
            for (int i = 0; i < chksSFieldConditions.ItemCount; i++)
                chksSFieldConditions.SetItemChecked(i, true);
            //
            if (dtPK.Rows.Count > 1)
                chkSLinkedTable.Checked = true;
            else
                chkSLinkedTable.Checked = false;
            chkInfoClass.Checked = true;
            //
            generateDefault();
            CreateColumns(trlSMethods);
            CreateNodes(trlSMethods);
            GenDefaultText();
        }
        private void CreateColumns(TreeList tl)
        {
            // Create three columns.
            tl.BeginUpdate();
            tl.Columns.Add();
            tl.Columns[0].Caption = "Name method";
            tl.Columns[0].VisibleIndex = 0;
            tl.EndUpdate();
        }

        private void CreateNodes(TreeList tl)
        {
            tl.BeginUnboundLoad();
            TreeListNode rootNode = null;
            // Create a root node .
            TreeListNode parentForRootNodes = null;
            string strDisplay = "";
            string strCondition = "";
            string str = "";
            for (int i = 0; i < sMethodNames.Count; i++)
            {
                parentForRootNodes = null; rootNode = null;
                strDisplay = "";
                if (!sWhereType[i].Equals("Delete"))
                {
                    strDisplay += "(" + sFieldDisplays[i].Rows.Count + "): ";
                    for (int j = 0; j < sFieldDisplays[i].Rows.Count - 1; j++)
                    {
                        strDisplay += sFieldDisplays[i].Rows[j]["COLUMN_NAME"].ToString() + ", ";
                    }
                    strDisplay += sFieldDisplays[i].Rows[sFieldDisplays[i].Rows.Count - 1]["COLUMN_NAME"];
                }
                else
                {
                    strDisplay += " * ";
                }
                strCondition = "";
                if (sFieldConditions[i].Rows.Count > 0)
                {
                    strCondition += "(" + sFieldConditions[i].Rows.Count + ") ";
                    for (int j = 0; j < sFieldConditions[i].Rows.Count - 1; j++)
                    {
                        strCondition += sFieldConditions[i].Rows[j]["COLUMN_NAME"].ToString() + " " + sWhereType[i] + " ";
                    }
                    strCondition += sFieldConditions[i].Rows[sFieldConditions[i].Rows.Count - 1]["COLUMN_NAME"];
                }
                else
                {
                    strCondition += " all";
                }
                rootNode = tl.AppendNode(
                   new object[] { sMethodNames[i] }, parentForRootNodes);
                tl.AppendNode(new object[] { "Description: " + sMethodDescription[i] }, rootNode);
                tl.AppendNode(new object[] { sMethodType[i].ToUpper() + " " + strDisplay }, rootNode);
                tl.AppendNode(new object[] { "Where: " + strCondition }, rootNode);
            }
            tl.EndUnboundLoad();
        }
        public bool isWhere(List<string> list, string search)
        {
            IEnumerable<string> query = list.Where(item => item.Equals(search));
            foreach (string VARIABLE in query)
            {
                return true;
            }
            return false;
        }
        string getPK()
        {
            string str = "";
            if (dtPK.Rows.Count > 0)
            {
                for (int i = 0; i < dtPK.Rows.Count - 1; i++)
                {
                    str += dtPK.Rows[i]["COLUMN_NAME"].ToString().Substring(0, 1).ToUpper() + dtPK.Rows[i]["COLUMN_NAME"].ToString().Substring(1)
                    + "And";
                } str += dtPK.Rows[dtPK.Rows.Count - 1]["COLUMN_NAME"].ToString().Substring(0, 1).ToUpper() + dtPK.Rows[dtPK.Rows.Count - 1]["COLUMN_NAME"].ToString().Substring(1)
                     ;
            }
            return str;
        }
        void generateDefault()
        {
            string name;
            //---------------------------------------------------------------------
            //select all
            dtDefault.Rows.Clear();
            DataTable dt1 = dtDefault.Clone();
            sMethodDescription.Add("Lấy ra tất cả các trường và các bản ghi");//pulled out all the fields and records 
            sMethodNames.Add("SelectAll");
            sWhereType.Add("");
            sFieldDisplays.Add(dt);
            sFieldConditions.Add(dt1);
            sMethodType.Add("Select");
            // select list by fk
            for (int i = 0; i < dtFK.Rows.Count; i++)
            {
                DataTable dt2 = dtDefault.Clone();
                dt2.ImportRow(dtFK.Rows[i]);
                sMethodNames.Add("SelectListBy" + dtFK.Rows[i]["COLUMN_NAME"].ToString().Substring(0, 1).ToUpper() + dtFK.Rows[i]["COLUMN_NAME"].ToString().Substring(1));
                sMethodDescription.Add("Lấy ra danh sách các bản ghi theo khóa ngoại " + dtFK.Rows[i]["COLUMN_NAME"]);
                sWhereType.Add("");
                sFieldDisplays.Add(dt);
                sFieldConditions.Add(dt2);
                sMethodType.Add("Select");
            }
            // select only by pk by and
            if (dtPK.Rows.Count > 0)
            {
                sMethodNames.Add("SelectOnlyBy" + getPK());
                sMethodDescription.Add("Lấy ra một bản ghi theo primary key");
                sWhereType.Add("and");
                sFieldDisplays.Add(dt);
                sFieldConditions.Add(dtPK);
                sMethodType.Add("Select");
            }
            // select only by unique
            for (int i = 0; i < dtUnique.Rows.Count; i++)
            {
                name = "SelectOnlyBy" + dtUnique.Rows[i]["COLUMN_NAME"].ToString().Substring(0, 1).ToUpper() +
                      dtUnique.Rows[0]["COLUMN_NAME"].ToString().Substring(1);
                if (!isWhere(sMethodNames, name))
                {
                    DataTable dt22 = dtDefault.Clone();
                    dt22.ImportRow(dtUnique.Rows[i]);
                    sMethodNames.Add("SelectOnlyBy" + dtUnique.Rows[i]["COLUMN_NAME"].ToString().Substring(0, 1).ToUpper() + dtUnique.Rows[i]["COLUMN_NAME"].ToString().Substring(1));
                    sMethodDescription.Add("Lấy ra một bản ghi theo unique " + dtUnique.Rows[i]["COLUMN_NAME"]);
                    sWhereType.Add("");
                    sFieldDisplays.Add(dt);
                    sFieldConditions.Add(dt22);
                    sMethodType.Add("Select");
                }
            }
            //end
            //---------------------------------------------------------------------
            //update only by pk
            if (dtPK.Rows.Count > 0)
            {
                sMethodDescription.Add("Cập nhập một bản ghi dữ liệu");
                sMethodNames.Add("UpdateOnlyBy" + getPK());
                sWhereType.Add("and");
                sFieldDisplays.Add(dtNotIdentitys);
                sFieldConditions.Add(dtPK);
                sMethodType.Add("Update");
            }
            // update only by unique
            for (int i = 0; i < dtUnique.Rows.Count; i++)
            {
                name = "UpdateOnlyBy" + dtUnique.Rows[i]["COLUMN_NAME"].ToString().Substring(0, 1).ToUpper() +
                      dtUnique.Rows[0]["COLUMN_NAME"].ToString().Substring(1);
                if (!isWhere(sMethodNames, name))
                {
                    DataTable dt31 = dtDefault.Clone();
                    dt31.ImportRow(dtUnique.Rows[i]);
                    sMethodNames.Add(name);
                    sMethodDescription.Add("Cập nhập một bản ghi theo unique " + dtUnique.Rows[i]["COLUMN_NAME"]);
                    sWhereType.Add("");
                    sFieldDisplays.Add(dtNotIdentitys);
                    sFieldConditions.Add(dt31);
                    sMethodType.Add("Update");
                }
            }
            //end
            //---------------------------------------------------------------------
            //delete all
            //sMethodDescription.Add("Xóa tất cả các bản ghi");
            //sMethodNames.Add("DeleteAll");
            //sWhereType.Add("");
            //sFieldDisplays.Add(dt);
            //sFieldConditions.Add(dtDefault);
            //sMethodType.Add("Delete");
            // delete only by pk by and
            if (dtPK.Rows.Count > 0)
            {
                sMethodNames.Add("DeleteOnlyBy" + getPK());
                sMethodDescription.Add("Xóa một bản ghi theo primary key");
                sWhereType.Add("and");
                sFieldDisplays.Add(dt);
                sFieldConditions.Add(dtPK);
                sMethodType.Add("Delete");
            }
            // delete list by fk
            for (int i = 0; i < dtFK.Rows.Count; i++)
            {
                DataTable dt41 = dtDefault.Clone();
                dt41.ImportRow(dtFK.Rows[i]);
                sMethodNames.Add("DeleteListBy" + dtFK.Rows[i]["COLUMN_NAME"].ToString().Substring(0, 1).ToUpper() + dtFK.Rows[i]["COLUMN_NAME"].ToString().Substring(1));
                sMethodDescription.Add("Xóa danh sách các bản ghi theo khóa ngoại " + dtFK.Rows[i]["COLUMN_NAME"]);
                sWhereType.Add("");
                sFieldDisplays.Add(dt);
                sFieldConditions.Add(dt41);
                sMethodType.Add("Delete");
            }

            // delete only by unique
            for (int i = 0; i < dtUnique.Rows.Count; i++)
            {
                name = "DeleteOnlyBy" + dtUnique.Rows[i]["COLUMN_NAME"].ToString().Substring(0, 1).ToUpper() +
                      dtUnique.Rows[0]["COLUMN_NAME"].ToString().Substring(1);
                if (!isWhere(sMethodNames, name))
                {
                    DataTable dt4 = dtDefault.Clone();
                    dt4.ImportRow(dtUnique.Rows[i]);
                    sMethodNames.Add(name);
                    sMethodDescription.Add("Xóa một bản ghi theo unique " + dtUnique.Rows[i]["COLUMN_NAME"]);
                    sWhereType.Add("");
                    sFieldDisplays.Add(dt);
                    sFieldConditions.Add(dt4);
                    sMethodType.Add("Delete");
                }
            }
            //---------------------------------------------------------------------
            //insert all

            sMethodDescription.Add("Thêm dữ liệu vào tất cả các trường và các bản ghi");
            sMethodNames.Add("Insert");
            sWhereType.Add("");
            sFieldDisplays.Add(dtNotIdentitys);
            sFieldConditions.Add(dtDefault);
            sMethodType.Add("Insert");
            //---------------------------------------------------------------------
            //page all

            if (cbbGenerateOption.SelectedIndex == 0)
            {
                sMethodDescription.Add("Phân trang lấy tất cả các trường và các bản ghi");//pulled out all the fields and records 
                sMethodNames.Add("PagesAll");
                sWhereType.Add("");
                sFieldDisplays.Add(dt);
                sFieldConditions.Add(dtDefault);
                sMethodType.Add("Page");
                //page list by fk
                for (int i = 0; i < dtFK.Rows.Count; i++)
                {
                    DataTable dt5 = dtDefault.Clone();
                    dt5.ImportRow(dtFK.Rows[i]);
                    sMethodNames.Add("PagesListBy" + dtFK.Rows[i]["COLUMN_NAME"].ToString().Substring(0, 1).ToUpper() + dtFK.Rows[i]["COLUMN_NAME"].ToString().Substring(1));
                    sMethodDescription.Add("Phân trang lấy ra danh sách các bản ghi theo khóa ngoại " + dtFK.Rows[i]["COLUMN_NAME"]);
                    sWhereType.Add("");
                    sFieldDisplays.Add(dt);
                    sFieldConditions.Add(dt5);
                    sMethodType.Add("Page");
                }

            }
        }
        void setValuesTabCustomer(string text)
        {
            int vt = 0;
            for (int i = 0; i < sMethodNames.Count; i++)
            {
                if (sMethodNames[i].Equals(text))
                {
                    vt = i;
                    break;
                }
            }
            txtSNameMethods.Text = text;
            txtDescriptionMethods.Text = sMethodDescription[vt];
            int k = sWhereType[vt].Equals("") ? 0 : sWhereType[vt].Equals("and") ? 1 : 2;
            rdoWheretype.SelectedIndex = k;
            if (chksSFielDisplayed.ItemCount == sFieldDisplays[vt].Rows.Count)
            {
                chksFieldSelect.Items[0].CheckState = CheckState.Checked;
            }
            else
            {
                chksFieldSelect.Items[0].CheckState = CheckState.Unchecked;
            }
            if (chksSFieldConditions.ItemCount == sFieldConditions[vt].Rows.Count)
            {
                chksFieldSelect.Items[1].CheckState = CheckState.Checked;
            }
            else
            {
                chksFieldSelect.Items[1].CheckState = CheckState.Unchecked;
            }
            cbbType.Text = sMethodType[vt];
            bool check = true;
            for (int i = 0; i < chksSFielDisplayed.ItemCount; i++)
            {
                check = false;
                for (int j = 0; j < sFieldDisplays[vt].Rows.Count; j++)
                {
                    if (chksSFielDisplayed.GetItemValue(i).Equals(
                            sFieldDisplays[vt].Rows[j]["COLUMN_NAME"].ToString()))
                    {
                        check = true;
                        chksSFielDisplayed.SetItemChecked(i, check);
                        break;
                    }
                }
                if (!check)//check=false;
                {
                    chksSFielDisplayed.SetItemChecked(i, check);
                }
            }
            check = true;
            for (int i = 0; i < chksSFieldConditions.ItemCount; i++)
            {
                check = false;
                for (int j = 0; j < sFieldConditions[vt].Rows.Count; j++)
                    if (chksSFieldConditions.GetItemValue(i).Equals(sFieldConditions[vt].Rows[j]["COLUMN_NAME"].ToString()))
                    {
                        check = true;
                        chksSFieldConditions.SetItemChecked(i, check);
                        break;
                    }
                if (!check)//check=false;
                {
                    chksSFieldConditions.SetItemChecked(i, check);
                }
            }
        }

        private void checkedListBoxControl1_SelectedValueChanged(object sender, DevExpress.XtraEditors.Controls.ItemCheckEventArgs e)
        {
            if (chksFieldSelect.SelectedValue != null)
            {
                if (chksFieldSelect.SelectedValue.ToString().Equals("display"))
                {
                    if (chksFieldSelect.Items[0].CheckState == CheckState.Checked)
                    {
                        for (int i = 0; i < chksSFielDisplayed.ItemCount; i++)
                            chksSFielDisplayed.SetItemChecked(i, true);
                    }
                    else if (chksFieldSelect.Items[0].CheckState == CheckState.Unchecked)
                    {
                        for (int i = 0; i < chksSFielDisplayed.ItemCount; i++)
                            chksSFielDisplayed.SetItemChecked(i, false);
                    }
                }
                else
                {
                    if (chksFieldSelect.Items[1].CheckState == CheckState.Checked)
                    {
                        for (int i = 0; i < chksSFieldConditions.ItemCount; i++)
                            chksSFieldConditions.SetItemChecked(i, true);
                    }
                    else if (chksFieldSelect.Items[1].CheckState == CheckState.Unchecked)
                    {
                        for (int i = 0; i < chksSFieldConditions.ItemCount; i++)
                            chksSFieldConditions.SetItemChecked(i, false);
                    }
                }
            }
        }

        private void bntChangeDefault_Click(object sender, EventArgs e)
        {
            init();
        }

        private void trlSMethods_FocusedNodeChanged(object sender, FocusedNodeChangedEventArgs e)
        {
            TreeListNode node = trlSMethods.Selection[0];
            try
            {
                if (node.Level == 0)
                {
                    setValuesTabCustomer(node.GetDisplayText("Name method"));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void bntGenerate_Click(object sender, EventArgs e)
        {
            GenDefaultText();
        }
        void GenDefaultText()
        {
            if (sMethodNames.Count > 0)
            {
                switch (cbbLanguages.SelectedItem.ToString())
                {
                    case "C# Three layer":
                        gencodeSharp gen = new gencodeSharp(chkInfoClass.Checked, dtPK,
                            txtSproc.Text, comboBoxEdit1.Text, txtTableName.Text, txtUserClass.Text,
                            txtDescriptionClass.Text, txtView.Text, txtDTO.Text, txtBLL.Text,
                            txtDAL.Text, txtDataAccessLayer.Text, txtDataObjectLayer.Text,
                            txtBusinessLogicLayer.Text, txtPresentationLayer.Text,
                            txtNamespaceParent.Text, sMethodType, sWhereType,
                            sMethodDescription, sMethodNames, dt,
                            sFieldDisplays, sFieldConditions,
                            cbbCnData.Text);
                        txtVIEWS.Text = gen.GenerateClassView();
                        txtBLLS.Text = gen.GenerateClassBLL();
                        txtDTOS.Text = gen.GenerateClassDTO();
                        txtDALS.Text = gen.GenerateClassDAL();
                        txtSPROCS.Text = gen.GenerateSprocs();
                        break;
                }
            }
            else
            {
                MessageBox.Show("Không có một method nào được khởi tạo", "Thông báo", MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation);
            }
        }
        private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Gobal.saveFileDialog(txtTableName.Text + txtView.Text + ".txt", txtVIEWS.Text);
        }
        private void simpleButton2_Click(object sender, EventArgs e)
        {
            string date = "";
            string path = "";
            try
            {
                GenDefaultText();
                FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
                folderBrowserDialog1.Description = "Chose folder save list file of " + table;
                // folderBrowserDialog1.RootFolder = Environment.SpecialFolder.Personal;
                if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
                {
                    date = string.Format("{0:hhmmss_ddMMyyyy}", DateTime.Now);
                    path = folderBrowserDialog1.SelectedPath + "\\" + txtTableName.Text + "_" + date;
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    Gobal.writeFile(path + "\\" + txtTableName.Text + txtBLL.Text + ".cs", txtBLLS.Text);
                    Gobal.writeFile(path + "\\" + txtTableName.Text + txtDAL.Text + ".cs", txtDALS.Text);
                    Gobal.writeFile(path + "\\" + txtTableName.Text + txtDTO.Text + ".cs", txtDTOS.Text);
                    Gobal.writeFile(path + "\\" + txtTableName.Text + txtView.Text + ".txt", txtVIEWS.Text);
                    Gobal.writeFile(path + "\\" + txtSproc.Text + txtTableName.Text + ".sql", txtSPROCS.Text);
                    MessageBox.Show("Create list files completed successfully", "Message", MessageBoxButtons.OK,
                                 MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                if (Directory.Exists(path))
                {
                    Directory.Delete(path, true);
                }
                MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK,
                                MessageBoxIcon.Warning);
            }
        }

        private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

            Gobal.saveFileDialog(txtTableName.Text + txtBLL.Text + ".css", txtBLLS.Text);
        }

        private void barButtonItem4_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Gobal.saveFileDialog(txtTableName.Text + txtDTO.Text + ".css", txtDTOS.Text);
        }

        private void barButtonItem3_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Gobal.saveFileDialog(txtTableName.Text + txtDAL.Text + ".css", txtDALS.Text);
        }

        private void barButtonItem5_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string date = string.Format("{0:ddMMyyyy}", DateTime.Now);
            Gobal.saveFileDialog(txtSproc.Text + txtTableName.Text + "_" + date + ".sql", txtDALS.Text);
        }
    }
}
